#include <iostream>
#include "FD.H"
#include "FR.H"
#include "CImgWrapper.h"
#include "cmdline.h"
#include "facesdkwrapper.h"
#include "file_utilits.h"
#include "string_utils.h"
using namespace gdface;
using namespace std;
using namespace cimg_library;
const static string SUFFIX_JPG=".jpg";
const static string SUFFIX_JPEG=".jpeg";
bool jpeg_is_folder;
void detect_face(const cmdline::parser &parser,const string &file){
	facesdk_wrapper wrapper;
	CImgWrapper<uint8_t> cimg;
	auto jpeg_data=gdface::load_binary_file(file.data());
	cimg.load_mem_jpeg(jpeg_data);
	CImgWrapper<uint8_t> cimg_gray;
	cimg_gray.load_mem_jpeg_gray(jpeg_data);
	auto min_size=parser.get<int16_t>("min");
	FSize min{min_size,min_size};
	auto max_size=int16_t(std::min(parser.get<float>("max"),1.0f)*std::min(cimg_gray._width,cimg_gray._height));
	max_size=std::max(max_size,min_size);
	FSize max{max_size,max_size};
	auto test_count = jpeg_is_folder ? 1 : parser.get<int>("count");
	face_info_type res;
	tls_clock_probe.start();
	for (decltype(test_count) i = 0; i < test_count; ++i) {
		res = wrapper.detect_face(cimg_gray, parser.exist("eye"), parser.get<double>("scale"), min, max);
	}
	auto time_cost = tls_clock_probe.end() / test_count;
	wrapper.display_face_rect(cimg,res,true, "IPP:",test_count, " times,average=", time_cost, " seconds");

}
int main(int argc, char * argv[]) {
	cmdline::parser parser;	
	parser.add<std::string>("jpeg", 'j', "jpeg image file or folder has jpeg file", true);
	parser.add("count", 'c', "test count,invalid only jpeg is file", false, int(1));
	parser.add<double>("scale", 's', "scale ratio", false, 1.1);
	parser.add<int16_t>("min", '\0', "min detect win size,default 40x40", false, int16_t(40));
	parser.add<float>("max", '\0', "min detect win size,default 0.7xmin(width,height)", false, .7f);
	parser.add("eye", '\0', "detect eye also");
	parser.parse_check(argc, argv);

	try{
		jpeg_is_folder = is_folder(parser.get<string>("jpeg"));
		if(jpeg_is_folder){
			for_each_file(parser.get<string>("jpeg"),
				[&](const char*path,const char* name){
				auto full_path=string(path).append({file_sepator()}).append(name);
					std::string lower_name=tolower(std::string(name));
					if(end_with(lower_name,SUFFIX_JPG)||end_with(lower_name,SUFFIX_JPEG)){
						detect_face(parser,full_path);
					}
				return false;
			},true);
		}
		else {
			detect_face(parser, parser.get<string>("jpeg"));
		}
			
	}catch(std::exception &e){
		cout<<"exception:"<<e.what()<<endl;
	}catch(...){
		cout<<"exception:unknow"<<endl;
	}

}
